package edu.hcmus.sow.web.user;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import edu.hcmus.sow.domain.User;

@Component
public class UserValidator implements Validator {

   // ~ Methods
   // ========================================================================================================

   public boolean supports(Class<?> clazz) {
      return clazz.equals(User.class);
   }

   public void validate(Object obj, Errors errors) {
      User uf = (User) obj;

      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "field.required", "Required field");
      if (!errors.hasFieldErrors("username")) {
         if (uf.getUsername().length() < 3 || uf.getUsername().length() > 50)
            errors.rejectValue("username", "not_zero", "Username 3-50 characters is required. *");
      }

      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.required", "Required field");
      if (!errors.hasFieldErrors("password")) {
         if (uf.getPassword().length() < 6 || uf.getPassword().length() > 12)
            errors.rejectValue("password", "not_zero", "Password 6-12 characters is required. *");
      }

      // if ((uf.getUsername() == null) || (uf.getUsername().length() < 3) ||
      // (uf.getUsername().length() > 50)) {
      // errors.rejectValue("username", "err.username", "Username 3-50 characters is required. *");
      // }
      //
      // if ((uf.getPassword() == null) || (uf.getPassword().length() < 6) ||
      // (uf.getPassword().length() > 12)) {
      // errors.rejectValue("password", "err.password", "Password 6-12 characters is required. *");
      // }

   }
}
